﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Linq;
using IndexMarkSilverlightClient;
using IndexMarkSilverlightClient.Classes;
using System.ComponentModel;
using IndexMarkSilverlightClient.IndexMarkServiceReference;
using SharedCode;
using System.Collections.Generic;

namespace IndexMarkSilverlightClient.Views
{

    public class AddAnswerViewModel : ViewModelBase
    {

        #region DataMembers

        IndexMarkServiceClient client = new IndexMarkServiceClient();

        private Answer answer = new Answer();

        public Answer Answer
        {
            get
            {
                return answer;
            }
            set
            {
                answer = value;
                PropertyChangedInit(() => this.Answer);
            }
        }

        private Characteristic currentChar = null;

        public Characteristic CurrentChar
        {
            get
            {
                return currentChar;
            }
            set
            {
                currentChar = value;
                PropertyChangedInit(() => this.CurrentChar);
                PropertyChangedInit(() => this.IsYesNoUnit);

                if (IsYesNoUnit)
                {
                    Answer.Volume = 1; //если "да/нет", то сразу ставим объем равным 1
                    AnswerChanged();
                }
            }
        }

        ObservableCollection<Gradation> gradations = new ObservableCollection<Gradation>();

        public ObservableCollection<Gradation> Gradations
        {
            get
            {
                return gradations;
            }
            set
            {
                gradations = value;
                PropertyChangedInit(() => this.Gradations);
                PropertyChangedInit(() => this.IsGraduated);
            }
        }

        public void FillGradationForNewAnswer()
        {
            //заполняем градации в ансвере по количеству пришедших градационных групп
            int i = 0;
            var indexes = new List<int>();
            var FindIndexes = new List<int>();
            foreach (Gradation G in gradations)
            {
                foreach (Gradation GA in answer.Gradations)
                {
                    if (G.FindInChild(GA) != null)
                    {
                        if (!indexes.Contains(i))
                        {
                            indexes.Add(i);
                        }
                    }
                }

                i++;
            }

            for (int j = 0; j < gradations.Count; j++)
            {
                if (!indexes.Contains(j))
                {
                    FindIndexes.Add(j);
                }
            }

            foreach (int j in FindIndexes)
            {
                answer.Gradations.Insert(j, new Gradation
                {
                    Volume = 0
                });
            }

            PropertyChangedInit(() => this.Answer);
        }

        private Term currentTerm = null;

        public Term CurrentTerm
        {
            get
            {
                return currentTerm;
            }
            set
            {
                currentTerm = value;
            }
        }

        private bool isGraduated = true;

        public bool IsGraduated
        {
            get
            {
                return gradations.Count != 0;
            }
        }

        public bool IsYesNoUnit
        {
            get
            {
                if (currentChar == null) return false;
                return currentChar.Unit == "да/нет";
            }
        }

        public bool IsCorrect
        {
            get
            {
                bool GradationsCorrect = false;
                if (Gradations.Count == 0)
                    GradationsCorrect = true;

                foreach (var gradation in Gradations)
                {
                    if (gradation.IsCorrect)
                    {
                        GradationsCorrect = true;
                    }
                }
                return Answer.IsCorrect && GradationsCorrect;
            }
        }

        #endregion

        public AddAnswerViewModel()
        {
            this.answer = new Answer();
            client.GetGradationsCompleted += new EventHandler<GetGradationsCompletedEventArgs>(client_GetGradationsCompleted);
        }

        void client_GetGradationsCompleted(object sender, GetGradationsCompletedEventArgs e)
        {
            Gradations = e.Result;
            this.LoadCompletedInit(typeof(Gradation));
        }

        /// <summary>
        /// Загружает с сервера связанные градации
        /// </summary>
        public void LoadRelationGradation()
        {
            client.GetGradationsAsync(this.currentChar.ID);
        }

        public Gradation GetParent(Gradation Child)
        {
            foreach (Gradation G in Gradations)
            {
                Gradation Result = G.FindInChild(Child);
                if (Result != null)
                {
                    return G;
                }
            }

            return null;
        }

        public void AnswerChanged()
        {
            //this.PropertyChangedInit(() => this.Answer);
            PropertyChangedInit(() => IsCorrect);
        }

        public void GradationsChanged()
        {
            PropertyChangedInit(() => this.Gradations);
            foreach (Gradation G in Gradations)
            {
                G.PropertyChangedInit("IsCorrect");
            }
            PropertyChangedInit(() => IsCorrect);
        }

        public void RemoveNullGradations()
        {
            var RemoveGradations = answer.Gradations.Where(x => (x.ID == 0) || (x.Childs.Count == 0 && String.IsNullOrEmpty(x.Group) && x.Volume <= 0));
            for (int i = 0; i < answer.Gradations.Count; i++)
            {
                if (RemoveGradations.Contains(answer.Gradations[i]))
                {
                    answer.Gradations.RemoveAt(i);
                    i--;
                }
            }
        }
    }
}
